package com.ktwlrj.core.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ktwlrj.core.util.ContextHolderUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * 自定义填充公共字段处理类
 *
 * @author zhouxuanhong
 * @date 2019-04-03 18:12
 * @since JDK1.8
 */
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Autowired
    private ContextHolderUtils contextHolderUtils;

    @Override
    public void insertFill(MetaObject metaObject) {
        // 自动注入创建信息
        Object createTime = getFieldValByName("createTime", metaObject);
        if (createTime == null) {
            this.setInsertFieldValByName("createTime", new Date(), metaObject);
        }
        Object createUser = getFieldValByName("createUser", metaObject);
        if (createUser == null) {
            String userId = contextHolderUtils.getUserId();
            this.setInsertFieldValByName("createUser", userId, metaObject);
        }

        Object createUserName = getFieldValByName("createUserName", metaObject);
        if (createUserName == null) {
            String userName = contextHolderUtils.getRealName();
            this.setInsertFieldValByName("createUserName", userName, metaObject);
        }

        // 自动注入唯一索引帮助字段(新建为1)
        Object indexHelp = getFieldValByName("indexHelp", metaObject);
        if (indexHelp == null) {
            this.setInsertFieldValByName("indexHelp", "1", metaObject);
        }
    }


    @Override
    public void updateFill(MetaObject metaObject) {
        // 自动注入更新信息
        Object modifyTime = getFieldValByName("modifyTime", metaObject);
        if (modifyTime == null) {
            this.setUpdateFieldValByName("modifyTime", new Date(), metaObject);
        }
        Object modifyUser = getFieldValByName("modifyUser", metaObject);
        if (modifyUser == null) {
            String userId = contextHolderUtils.getUserId();
            this.setUpdateFieldValByName("modifyUser", userId, metaObject);
        }

        Object modifyUserName = getFieldValByName("modifyUserName", metaObject);
        if (modifyUserName == null) {
            String userName = contextHolderUtils.getRealName();
            this.setUpdateFieldValByName("modifyUserName", userName, metaObject);
        }
    }
}